var utils = require('../../utils/util.js');
var app = getApp();
Page({
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult:{},
    containerShow: true,
    searchShow: false
  },
  onLoad: function(event) {
    var inTheatersUrl = app.globalData.doubanBase + "/v2/movie/in_theaters" + "?start=0&count=3";
    var comingSoonUrl = app.globalData.doubanBase + "/v2/movie/coming_soon" + "?start=0&count=3";
    var top250Url = app.globalData.doubanBase + "/v2/movie/top250" + "?start=0&count=3";
    this.getMovieListData(inTheatersUrl, "inTheaters", '即将上映');
    this.getMovieListData(comingSoonUrl, "comingSoon", '正在热映');
    this.getMovieListData(top250Url, "top250", '豆瓣TOP250');
  },
  onMoreTap: function(event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category=' + category,
    })
  },
  onMovieTap:function(event){
    var movieId = event.currentTarget.dataset.movieid;
    console.log()
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id='+ movieId,
    })
  },
  getMovieListData: function(url, settedKey, categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      data: {},
      method: "Get",
      header: {
        "Content-Type": "json"
      },
      success: function(res) {
        //console.log(res)
        that.processDoubanData(res.data, settedKey, categoryTitle)
      },
      fail: function() {
        console.log(error)
      }
    })
  },
  bindfocus: function(event) {
    this.setData({
      containerShow: false,
      searchShow: true
    })

  },
  bindconfirm: function(event) {
    var text = event.detail.value;
    var searchUrl = app.globalData.doubanBase + "/v2/movie/search?q=" + text;
    this.getMovieListData(searchUrl,"searchResult","");
    console.log(searchUrl)
  },
  cancleContainerTap: function(event) {
    this.setData({
      containerShow: true,
      searchShow: false,
      searchResult:{}
    })
  },
  //数据绑定
  //moviesDouban接收的是res.data
  processDoubanData: function(moviesDouban, settedKey, categoryTitle) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
        //截取前六位剩下的字用省略号代替
      }
      var temp = {
        moviestars: utils.convertToStarsArray(subject.rating.stars),
        title: title,
        movieaverage: subject.rating.average,
        moviecoverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp);
    }
    var readyData = {};
    readyData[settedKey] = {
      categoryTitle: categoryTitle,
      movies: movies
    }
    this.setData(readyData)
  }


})